package com.securityLearn.sessionAuth.service.impl;

import com.securityLearn.sessionAuth.entity.UserDto;
import com.securityLearn.sessionAuth.service.AuthenticationService;
import com.securityLearn.sessionAuth.service.request.AuthenticationRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 认证服务
 *
 * @author duzq
 * @date 2021-8-26 20:50:31
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Override
    public UserDto authentication(AuthenticationRequest request) {
        if (ObjectUtils.isEmpty(request)
                || ObjectUtils.isEmpty(request.getUserName())
                || ObjectUtils.isEmpty(request.getPassword())) {
            throw new RuntimeException("账号或密码为空");
        }
        UserDto user = userMap.get(request.getUserName());
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("查询不到该用户");
        }
        if (!user.getPassword().equals(request.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }
        return user;
    }

    /**
     * 初始化用户信息
     */
    private Map<String, UserDto> userMap = new HashMap<>(2);

    {
        Set<String> zhangsan = new HashSet<>();
        zhangsan.add("p1");

        Set<String> lisi = new HashSet<>();
        lisi.add("p2");

        userMap.put("zhangsan", new UserDto("1010", "zhangsan", "123",
                "张三", "133443", zhangsan));
        userMap.put("lisi", new UserDto("1011", "lisi", "456",
                "李四", "144553", lisi));
    }
}
